//
//  FinancialServiceDetailViewController.m
//  Globalstone
//
//  Created by 刘建峰 on 16/7/19.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "FinancialServiceDetailViewController.h"
#import "SystemNumTableViewCell.h"
#import "BusinessProcessViewController.h"
static NSString * cellIndentifier = @"SystemNumTableViewCell";

@interface FinancialServiceDetailViewController ()<UITextViewDelegate,UITableViewDataSource,UITableViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UIScrollView *scroView;
@property (weak, nonatomic) IBOutlet UIView *attestView;
@property (weak, nonatomic) IBOutlet UIButton *maskButton;
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (weak, nonatomic) IBOutlet UILabel *placeHolder;
@property (weak, nonatomic) IBOutlet UIButton *doneButton;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (weak, nonatomic) IBOutlet UILabel *companyName;
@property (weak, nonatomic) IBOutlet UILabel *mainBusiness;
@property (weak, nonatomic) IBOutlet UILabel *companyAddress;
@property (weak, nonatomic) IBOutlet UILabel *moneyLimit;
@property (weak, nonatomic) IBOutlet UILabel *attestLimit;
@property (weak, nonatomic) IBOutlet UITextView *companyIntroduce;

@property(nonatomic,strong)NSMutableArray * supplyChainArray;

@property(nonatomic,strong)NSIndexPath * selectPath;

@property (weak, nonatomic) IBOutlet UITextField *moneyField;
@property (weak, nonatomic) IBOutlet UITextView *attesstTextView;


@end

@implementation FinancialServiceDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    _supplyChainArray = [NSMutableArray array];
    [self initViewLayout];
    [self getFinancialDetail];
    // Do any additional setup after loading the view.
}

- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.scroView];
    
    _textView.delegate = self;
    _scroView.contentSize = flexibleSize(CGSizeMake(0, 557), NO);
    
    _attestView.layer.cornerRadius = 10*VerticalRatio();
    _doneButton.layer.cornerRadius = 3*VerticalRatio();
    
    [_tableView registerNib:[UINib nibWithNibName:cellIndentifier bundle:nil] forCellReuseIdentifier:cellIndentifier];
    _tableView.dataSource = self;
    _tableView.delegate = self;
}

- (IBAction)back:(id)sender {
    [self backBtn];
}

#pragma mark === 申请贷款
- (IBAction)getService:(id)sender {
    
    NSInteger userType = [[Common getLoginInfo][@"userType"]integerValue];
    if (userType != 3) {
        UIAlertView * alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"对不起，您无权访问该版块" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
    _maskButton.hidden = NO;
    _attestView.hidden = NO;
    [self addRefreshing];
}

- (IBAction)hidehandel:(id)sender {
    _maskButton.hidden = YES;
    _attestView.hidden = YES;
}

#pragma mark  ==== 确认申请
- (IBAction)doneHandel:(id)sender {
   
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return ;
    }
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    
    NSString * lan = [InternationalControl userLanguage];
    if ([lan isEqualToString:@"en"]) {
        [dic setObject:@"2" forKey:@"language"];
    }else{
        [dic setObject:@"1" forKey:@"language"];
    }
    [dic setObject:_financialId forKey:@"fappCompanyId"];
    [dic setObject:_moneyField.text forKey:@"fappPrice"];
    [dic setObject:_attesstTextView.text forKey:@"fappContent"];
    
    if (_selectPath) {
        NSDictionary * dict = _supplyChainArray[_selectPath.row];
        
        [dic setObject:dict[@"orderType"] forKey:@"fappOrderType"];
        [dic setObject:dict[@"orderId"] forKey:@"fappOrderId"];
       [dic setObject:@"2" forKey:@"fappLoanStatus"];
    }else{
        [dic setObject:@"" forKey:@"fappOrderType"];
        [dic setObject:@"" forKey:@"fappOrderId"];
        [dic setObject:@"1" forKey:@"fappLoanStatus"];
    }
    
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:GS_applyForLoan withHttpType:@"POST" withTag:GS_GS_applyForLoan];
}


#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getMySupplyChainList];
        });
    }];
    [_tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.supplyChainArray.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求订单数据
            [self getMySupplyChainList];
        });
    }
    
}



#pragma mark == 申请贷款查询系统单号
- (void)getMySupplyChainList{
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return ;
    }
    
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    
    NSString * lan = [InternationalControl userLanguage];
    if ([lan isEqualToString:@"en"]) {
        [dic setObject:@"2" forKey:@"language"];
    }else{
        [dic setObject:@"1" forKey:@"language"];
    }
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:GS_queryMySupplyChainList withHttpType:@"POST" withTag:GS_GS_queryMySupplyChainList];
    
}

#pragma mark == 金融服务公司详情
- (void)getFinancialDetail{
    if (![Common getLoginStatus]) {
        [[AppDelegate sharedAppDelegate]ShowLoginPage];
        return ;
    }
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"museId"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"msadMemberId"];
    [dic setObject:[Common getLoginInfo][Key_User_password] forKey:@"musePwd"];
    [dic setObject:[Common getLoginInfo][Key_User_onlineKey] forKey:@"museOnlineTag"];
    [dic setObject:_financialId forKey:@"fcomId"];
    
    NSString * lan = [InternationalControl userLanguage];
    if ([lan isEqualToString:@"en"]) {
        [dic setObject:@"2" forKey:@"language"];
    }else{
        [dic setObject:@"1" forKey:@"language"];
    }
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:GS_queryFinacialCompanyDetail withHttpType:@"POST" withTag:GS_GS_queryFinacialCompanyDetail];
    
}

#pragma mark ==== 业务流程
- (IBAction)businessProcess:(UIButton *)sender {
    UIStoryboard * storyBoard = [UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    BusinessProcessViewController * page = [storyBoard instantiateViewControllerWithIdentifier:@"BusinessProcess"];
    page.type = [NSString stringWithFormat:@"%ld",sender.tag-100];
    page.companyId = _financialId;
    [[Common getNavigation]pushViewController:page];

}


#pragma mark - <UITextViewDelegate>

- (void)textViewDidChange:(UITextView *)textView{
    
    if (self.textView.text.length > 0) {
        self.placeHolder.hidden = YES;
    }else{
        self.placeHolder.hidden = NO;
    }
    
}


#pragma mark  ==== tableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _supplyChainArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 38*VerticalRatio();
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    SystemNumTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    if (cell == nil) {
        cell = [[SystemNumTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
    }
    [cell.number setTitle:[NSString stringWithFormat:@"%@",_supplyChainArray[indexPath.row][@"orderSysId"]] forState:UIControlStateNormal];
    cell.number.selected = NO;
    if (_selectPath && _selectPath.row ==indexPath.row) {
        cell.number.selected = YES;
    }
    cell.choseBlock = ^(){
        if (_selectPath && _selectPath.row != indexPath.row) {
            SystemNumTableViewCell * Cell = [_tableView cellForRowAtIndexPath:_selectPath];
            Cell.number.selected = NO;
        }
        _selectPath = indexPath;
    };
    
    return cell;
}



#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
    if (tag == GS_GS_queryFinacialCompanyDetail){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            NSDictionary * dic = database[@"result"];
            _companyName.text = [NSString stringWithFormat:@"%@",dic[@"fcomName"]];
            _companyAddress.text = [NSString stringWithFormat:@"%@",dic[@"fcomAddress"]];
            _mainBusiness.text = [NSString stringWithFormat:@"%@",dic[@"fcomMainBusi"]];
            _moneyLimit.text = [NSString stringWithFormat:@"%@",dic[@"fcomLoanLimit"]];
            _attestLimit.text = [NSString stringWithFormat:@"%@",dic[@"fcomCondition"]];
            _companyIntroduce.text = [NSString stringWithFormat:@"%@",dic[@"fcomContent"]];
        }
    }else if (tag == GS_GS_queryMySupplyChainList){
            if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
                
                [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
                
            }else  {
                dispatch_async(dispatch_get_main_queue(), ^{
                    _totle = [database[@"result"][@"total"] integerValue];
                    if (_totle > PageSize) {
                        __weak __typeof(self) weakSelf = self;
                        if (!self.tableView.footer) {
                            // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                            self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                                [weakSelf loadMoreData];
                            }];
                        }
                    }
                    if (self.pageNO == 1) {
                        [self.supplyChainArray removeAllObjects];
                    }
                    NSArray *arr = database[@"result"][@"list"];
                    for (id entity in arr) {
                        [self.supplyChainArray addObject:entity];
                    }
                    
                    [_tableView reloadData];
                    
                });
            }
    }else if (tag == GS_GS_applyForLoan){
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            _maskButton.hidden = YES;
            _attestView.hidden = YES;
              [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
        }
    }
}

-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    [_tableView.header endRefreshing];
    [_tableView.footer endRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
